<template>
  <div class="container f-c">
    <div class="menu" v-if="isLogin">
      <RouterLink to="/home">
        <el-button type="primary">客单核算</el-button>
      </RouterLink>
      <div class="right">
        <RouterLink to="/Order"><el-button type="primary">营业汇总</el-button></RouterLink>
        <RouterLink to="/option"><el-button type="primary">成本数据</el-button></RouterLink>
        <el-button @click="onLogout" type="primary">退出登录</el-button>
      </div>
    </div>
    <div class="container-bottom">
      <router-view />
    </div>
  </div>
</template>

<script setup>
import { nextTick, onMounted } from 'vue'
import { RouterLink, RouterView } from 'vue-router'
import { useRoute, useRouter } from 'vue-router'
import { getStore, setStore } from '@renderer/utils/localStorage.js'
import { optionInfo, pageColorList } from '@renderer/views/option.js'
import { useUserStore } from '@renderer/stores/user'
import { useUserDB } from '@renderer/database/useUserDB'

const { login, updateUserOptionInfo, addPageColor } = useUserDB()

const userStore = useUserStore()
const route = useRoute()
const router = useRouter()

const isLogin = computed(() => {
  console.log(route.path, userStore.isLogin, getStore('isLogin'))

  return userStore.isLogin || getStore('isLogin') == 1
})

function onLogout() {
  userStore.isLogin = false
  setStore('isLogin', 0)
  router.push('/')
}

onMounted(async () => {
  console.log(route.path, isLogin.value, userStore.optionInfo, userStore.currentUser)

  let currentUser = await login(userStore.currentUser?.userName)
  if (currentUser) {
    userStore.optionInfo = currentUser.optionInfo || {}
    userStore.pageColorList = currentUser.pageColorList || []

    if (isEmptyObject(userStore.optionInfo)) {
      userStore.optionInfo = optionInfo
      await updateUserOptionInfo(currentUser.userName, optionInfo)
    }
    // if (!userStore.pageColorList || userStore.pageColorList.length == 0) {
    userStore.pageColorList = pageColorList
    await addPageColor(currentUser.userName, pageColorList)
    // }
  }

  if (isLogin.value) {
    nextTick(() => {
      router.push('/home')
    })
  }
})

function isEmptyObject(obj) {
  return Object.keys(obj).length === 0
}
</script>

<style lang="scss" scoped>
.container {
  height: 100%;
  background-color: #fff;
  &-bottom {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
  }
}
.menu {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 16px 0 16px;
}
.right {
  display: flex;
  align-items: center;
  gap: 10px;
}
.upload-demo {
  width: 500px;
}
</style>
